package com.swa99ylum.pjv.validator;

import java.math.BigDecimal;
import java.util.Map;

import com.swa99ylum.pjv.exception.JSONValidateException;


/** <h1>数值范围 验证器</h1>
<br> 1、验证 value 必须为 数值类型 
<br> 2、验证 value 必须在 [min, max] 的 范围内 
<br> 
 */
public class NumberRangeValidator extends Validator {


	
	private BigDecimal max;
	private BigDecimal min;
	

	public NumberRangeValidator(String min, String max) {
		this(new BigDecimal(String.valueOf(min)), new BigDecimal(String.valueOf(max)));
	}
	public NumberRangeValidator(double min, double max) {
		this(new BigDecimal(min), new BigDecimal(max));
	}
	public NumberRangeValidator(int min, int max) {
		this(new BigDecimal(min), new BigDecimal(max));
	}
	public NumberRangeValidator(BigDecimal min, BigDecimal max) {
		super();
		this.max = max;
		this.min = min;
	}
	
	
	@Override
	public void doValidate(Object rootObject, String[] nodePath, String nodeName, Map<String, Object> parentValue, Object value) throws JSONValidateException {
		String valueStr = String.valueOf(value);
		
		if(!isNumeric(valueStr)) {
			throw new JSONValidateException(nodePath, value, "不为 数值类型");
			
		}else {
			
			BigDecimal bigDec = new BigDecimal(String.valueOf(value));
			
			if(bigDec.compareTo(min) < 0) throw new JSONValidateException(nodePath, value, "超出范围 [" +min + ", " + max + "]，小于最小值 " + min);
			if(bigDec.compareTo(max) > 0) throw new JSONValidateException(nodePath, value, "超出范围 [" +min + ", " + max + "]，大于最大值 " + max);
		}
		
		
	}
	
	public boolean isNumeric(String str) {
        try {
        	new BigDecimal(str);
        } catch (Exception e) {
            return false;//异常 说明包含非数字
        }
        return true;
    }
	
	
	
	public static void main(String[] args) {
		NumberRangeValidator nrv = new NumberRangeValidator(1, 1);
		
		
		System.out.println(nrv.isNumeric("asd"));
		System.out.println(nrv.isNumeric(""));
		System.out.println(nrv.isNumeric("  "));
		
		System.out.println("====");
		System.out.println(nrv.isNumeric("123"));
		System.out.println(nrv.isNumeric("-123"));
		System.out.println(nrv.isNumeric("12 3"));
		System.out.println(nrv.isNumeric("12.3"));
		
		
		System.out.println("====");
		BigDecimal a = new BigDecimal("2.00");
		BigDecimal b = new BigDecimal("2.0");
		BigDecimal c = new BigDecimal("2.1");
		
		System.out.println(a.compareTo(b));
		System.out.println(a.compareTo(c));//前者小于后者：返回 -1
		
		
		/**
		 * org.apache.commons.lang3.StringUtils 的 isNumeric() 方法 不够 准确
		 */
//		System.out.println(StringUtils.isNumeric("asd"));
//		System.out.println(StringUtils.isNumeric(""));
//		System.out.println(StringUtils.isNumeric("  "));
////		
////		System.out.println("====");
//		System.out.println(StringUtils.isNumeric("123"));
//		System.out.println(StringUtils.isNumeric("-123"));
//		System.out.println(StringUtils.isNumeric("12 3"));
//		System.out.println(StringUtils.isNumeric("12.3"));
	}

}
